package cn.hn3l.agriculture.services.servicesImplements;

import cn.hn3l.agriculture.dao.mapper.file.PictureMapper;
import cn.hn3l.agriculture.entitis.pictures.Picture;
import cn.hn3l.agriculture.services.interfaces.FileService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Attribute;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author Wang Weiwei
 * @Since 16-10-22
 * @Describe
 */
@Service("fileService")
public class FileServicesImplement implements FileService {
    @Resource
    private PictureMapper pictureMapper;

    public byte[] getPictureBytesById(int id) {
        return pictureMapper.findStreamById(id).getFile();
    }

    public Picture savePicture(Picture picture) {
        int point = pictureMapper.getNowId();
        picture.setId(point + 1);
        picture.setSrc(picture.getSrc() + picture.getId());
        pictureMapper.save(picture);
        return picture;
    }

    @Override
    public List<Picture> parseHTMLToPictureList(String pictureHtml) {
        List<Picture> pictureList = new ArrayList<>();
        Document document = Jsoup.parse(pictureHtml);
        Elements elements = document.getElementsByTag("img");
        for (Element element : elements){
            Picture picture = new Picture();
            String src = element.attr("src");
            picture.setSrc(src);
            //获取所有picture对象的id
            picture.setId(Integer.parseInt(
                    src.substring(src.lastIndexOf("/") + 1)));
            pictureList.add(picture);
        }

        return pictureList;
    }
}
